package sim.core.mvc;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sim.core.mvc.render.Render;
import sim.core.utils.ServletContextUtils;

/**
 * 所有Controller请求继承该类
 * 
 * @author Feny
 * @email 1220301855@qq.com
 * @version 1.0
 * @date 2018年5月21日下午2:52:25
 */
public class Model {

	public HttpServletRequest getRequest() {
		return ServletContextUtils.getRequest();
	}

	public HttpServletResponse getResponse() {
		return ServletContextUtils.getResponse();
	}

	/**
	 * 获取GET方式提交的数据中文乱码
	 * 
	 * @author Feny
	 * @date 2018年5月21日下午2:21:52
	 * @param arg
	 * @return
	 */
	public String getParam(String arg) {
		String param = this.getRequest().getParameter(arg);
		if (param == null) {
			return null;
		}
		try {
			return new String(param.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.out.printf("字符编码转换异常：%s\n", e.getMessage());
		}
		return param;
	}

	public Object getAttr(String name) {
		return this.getRequest().getAttribute(name);
	}

	public void setAttrAll(Map<String, Object> attrAll) {
		for (Entry<String, Object> entry : attrAll.entrySet()) {
			this.getRequest().setAttribute(entry.getKey(), entry.getValue());
		}
	}

	public void setAttr(String name, Object value) {
		this.getRequest().setAttribute(name, value);
	}

	public HttpSession getHttpSession() {
		return this.getRequest().getSession();
	}

	public Object getSession(String name) {
		return getHttpSession().getAttribute(name);
	}

	public void setSession(String name, Object value) {
		getHttpSession().setAttribute(name, value);
	}

	public void removeSession(String name) {
		getHttpSession().removeAttribute(name);
	}

	public void renderJsp(String view) {
		Render.renderJsp(view);
	}

	public void renderJson(Object data) {
		Render.renderJson(data);
	}

	public void renderJson(String jsonStr) {
		Render.renderJson(jsonStr);
	}

	public void renderXml(String xml) {
		Render.renderXml(xml);
	}

	public void renderHtml(String html) {
		Render.renderHtml(html);
	}

	public void renderJavaScript(String javaScript) {
		Render.renderJavaScript(javaScript);
	}

	public void renderText(String text) {
		Render.renderText(text);
	}

	public void renderFreeMarker(String tempPath) {
		Render.renderFreeMarker(tempPath);
	}

	public void redirect(String redirect) {
		Render.redirect(redirect);
	}
}
